package com.xysq.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalListDialog;
import com.rockcent.action.CallbackListener;
import com.rockcent.model.CustomerBO;
import com.rockcent.model.SchoolModel;
import com.umeng.analytics.MobclickAgent;
import com.xysq.XYApplication;
import com.xysq.adapter.DialogAdapter;
import com.xysq.lemon.R;
import com.xysq.util.Base64;
import com.xysq.util.PicUtil;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.ReleaseImageDialog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

/**
 * @Author huangdongkai
 * 用户资料
 */

public class UserActivity extends BaseActivity implements View.OnClickListener {
    private String schoolName;
    private int schoolId;
    private String loginName;
    private String uuid;
    private String date;

    @InjectView(R.id.txt_save)
    TextView saveTxt;
    @InjectView(R.id.edt_nickName)
    EditText nickNameEdt;
    @InjectView(R.id.edt_realName)
    EditText realNameEdt;
    @InjectView(R.id.edt_specialty)
    EditText specialtyEdt;
    @InjectView(R.id.edt_num)
    EditText numEdt;
    @InjectView(R.id.layout_date)
    RelativeLayout dateLayout;
    @InjectView(R.id.txt_date)
    TextView dateTxt;
    @InjectView(R.id.edt_address)
    EditText addressEdt;
    @InjectView(R.id.txt_school)
    TextView schoolTxt;
//    @InjectView(R.id.spinner_sex)
//    Spinner sexSpinner;
    @InjectView(R.id.txt_sex)
    TextView sexTxt;
    @InjectView(R.id.txt_school_id)
    TextView schoolIdTxt;
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.layout_loading)
    LinearLayout loadingLayout;
    @InjectView(R.id.layout_reloading)
    LinearLayout reloadingLayout;
    @InjectView(R.id.img_head)
    ImageView headImg;

    public static String flagDate = "date";
    public static String flagSchool = "school";
    public static final int SELECT_PICTURE = 2;
    public static final int TAKE_PHOTO = 4;
    public static final int GET_CUT_PICTURE = 3;
    private Uri takePhotoUri;
    private String dates[];
    private String schoolDatas[];
    private int schoolIDs[];
    private ReleaseImageDialog.Builder releaseImageDialogBuilder;
    private Dialog releaseImageDialog = null;
    String newHeadUrl;
    private static final double MAX_PIC_SIZE = 50;
    public static final int IDENTIFY_CODE = 0;
    public static final String RESULT = "result";
    private String value;
    public static final String INDEX = "index";
    private String index;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        initView();
        getDatas();
    }

    private void initView() {
        index = getIntent().getStringExtra(INDEX);
        sexTxt.setOnClickListener(this);
        sexTxt.setText("男");
        dateLayout.setOnClickListener(this);
        schoolTxt.setOnClickListener(this);
        saveTxt.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        headImg.setOnClickListener(this);
        nickNameEdt.addTextChangedListener(new MyTextWatcher(nickNameEdt));
        realNameEdt.addTextChangedListener(new MyTextWatcher(realNameEdt));
        specialtyEdt.addTextChangedListener(new MyTextWatcher(specialtyEdt));
        numEdt.addTextChangedListener(new MyTextWatcher(numEdt));
        addressEdt.addTextChangedListener(new MyTextWatcher(addressEdt));
    }

    private class MyTextWatcher implements TextWatcher {
        private EditText mEditText;

        public MyTextWatcher(EditText e) {
            mEditText = e;
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            value = mEditText.getText().toString();
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            int length = getLength(mEditText.getText().toString());
            switch (mEditText.getId()) {
                case R.id.edt_nickName:
                    if (length > 14) {
                        mEditText.setText(value);
                        return;
                    }
                    break;
                case R.id.edt_realName:
                    if (length > 12) {
                        mEditText.setText(value);
                        return;
                    }
                    break;
                case R.id.edt_specialty:
                    if (length > 20) {
                        mEditText.setText(value);
                        return;
                    }
                    break;
                case R.id.edt_num:
                    if (length > 20) {
                        mEditText.setText(value);
                        return;
                    }
                    break;
                case R.id.edt_address:
                    if (length > 100) {
                        mEditText.setText(value);
                        return;
                    }
                    break;
            }
        }
    }

    private void getDatas() {
        getCustomer();
        getSchools();
    }

    //查询用户信息
    private void getCustomer() {
        loginName = UserInfoKeeper.readPhoneNumber(this);
        appAction.getCustomer(loginName, "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                uuid = data.getUuid();
                if (!TextUtils.isEmpty(data.getName())) {
                    realNameEdt.setText(data.getName());
                    UserInfoKeeper.writeRealName(UserActivity.this, data.getName());
                } else {
                    UserInfoKeeper.writeRealName(UserActivity.this, "");
                }
                if (!TextUtils.isEmpty(data.getNickname())) {
                    nickNameEdt.setText(data.getNickname());
                }
                if (!TextUtils.isEmpty(data.getSchoolId())) {
                    schoolIdTxt.setText(data.getSchoolId());
                }
                if (!TextUtils.isEmpty(data.getSchoolName())) {
                    schoolTxt.setText(data.getSchoolName());
                }
                if (!TextUtils.isEmpty(data.getProfession())) {
                    specialtyEdt.setText(data.getProfession());
                }
                if (!TextUtils.isEmpty(data.getAddress())) {
                    addressEdt.setText(data.getAddress());
                }
                if (!TextUtils.isEmpty(data.getStudentNum())) {
                    numEdt.setText(data.getStudentNum());
                }
                if (!TextUtils.isEmpty(String.valueOf(data.getGrade()))) {
                    if (data.getGrade() != 0) {
                        dateTxt.setText(String.valueOf(data.getGrade()));
                    } else {
                        dateTxt.setText("2015");
                    }
                }

                if (!TextUtils.isEmpty(data.getSex())) {
                    sexTxt.setText(UseUtil.checkSex(data.getSex(), UserActivity.this));
//                    SpinnerAdapter apsAdapter = sexSpinner.getAdapter(); //得到SpinnerAdapter对象
//                    for (int i = 0; i < apsAdapter.getCount(); i++) {
//                        if (data.getHeadUrl().equals(String.valueOf(i + 1))) {
//                            sexSpinner.setSelection(i, true);// 默认选中项
//                            break;
//                        }
//                    }

                }
                if (!TextUtils.isEmpty(data.getHeadUrl()) && !data.getHeadUrl().equals("null")) {
                    newHeadUrl = data.getHeadUrl();
                    XYApplication.getImageLoader().displayImage(PropertiesUtil.getImageServer() + data.getHeadUrl(), headImg);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(UserActivity.this, message);
                loadingLayout.setVisibility(View.GONE);
                reloadingLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    private void getSchools() {
        appAction.getSchool(new CallbackListener<List<SchoolModel>>() {
            @Override
            public void onSuccess(List<SchoolModel> data) {
                if (data != null && data.size() > 0) {
                    schoolDatas = new String[data.size()];
                    schoolIDs = new int[data.size()];
                    SchoolModel schoolModel;
                    for (int i = 0; i < schoolDatas.length; i++) {
                        schoolModel = data.get(i);
                        schoolDatas[i] = schoolModel.getName();
                        schoolIDs[i] = schoolModel.getUuid();
                    }
                }
                loadingLayout.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(UserActivity.this, message);
                loadingLayout.setVisibility(View.GONE);
                reloadingLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.txt_save:
                saveInfo();
                break;
            case R.id.ibtn_back:
                Intent i = new Intent();
                i.putExtra(RESULT, false);
                setResult(IDENTIFY_CODE, i);
                finish();
                break;
            case R.id.layout_reloading:
                reloadingLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.VISIBLE);
                getCustomer();
                break;
            case R.id.txt_school:
                Intent intent = new Intent(this, WheelViewActivity.class);
                intent.putExtra(WheelViewActivity.DATAS, schoolDatas);
                intent.putExtra(WheelViewActivity.IDS, schoolIDs);
                intent.putExtra(WheelViewActivity.FLAG, flagSchool);
                startActivityForResult(intent, WheelViewActivity.CODE);
                break;
            case R.id.layout_date:
                Intent intentDate = new Intent(this, WheelViewActivity.class);
                dates = UseUtil.getDates();
                intentDate.putExtra(WheelViewActivity.DATE_IDENT, dates);
                intentDate.putExtra(WheelViewActivity.FLAG, flagDate);
                startActivityForResult(intentDate, WheelViewActivity.DATE);
                break;
            case R.id.img_head:
                createDialog();
                listenDialog();
                showReleaseImageDialog();
                break;
            case R.id.txt_sex:
                NormalListDialogNoTitle();
            default:
        }
    }

    private void createDialog() {
        releaseImageDialogBuilder = new ReleaseImageDialog.Builder(this);
        releaseImageDialog = releaseImageDialogBuilder.create();
    }

    private void listenDialog() {
        releaseImageDialogBuilder.pictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pictureChoose();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pressTakePhotoButton();
                releaseImageDialog.dismiss();
            }
        });
        releaseImageDialogBuilder.cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                releaseImageDialog.dismiss();
            }
        });
    }

    private void pictureChoose() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, SELECT_PICTURE);
    }

    private void pressTakePhotoButton() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
            takePhoto();
        } else {
            Toast.makeText(this, "没有SD卡", Toast.LENGTH_SHORT).show();
        }

        releaseImageDialog.dismiss();
    }

    private void takePhoto() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File appDir = new File(Environment.getExternalStorageDirectory(), "Xiaoyou");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File out = new File(appDir, "camera.jpg");
            takePhotoUri = Uri.fromFile(out);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
            startActivityForResult(intent, TAKE_PHOTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showReleaseImageDialog() {
        android.view.Window dialogWindow1 = releaseImageDialog.getWindow();
        android.view.WindowManager.LayoutParams lp1 = releaseImageDialog.getWindow().getAttributes();
        android.util.DisplayMetrics dm1 = new android.util.DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm1);
        dialogWindow1.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL);
        releaseImageDialog.getWindow().setAttributes(lp1);
        releaseImageDialog.show();
    }

    //修改保存用户信息
    private void saveInfo() {
        String obj = makeData();
        appAction.updateCustomer(obj, new CallbackListener<Boolean>() {
            @Override
            public void onSuccess(Boolean data) {
                ToastUtil.showShort(UserActivity.this, getResources().getString(R.string.toast_success_update_info));
                Intent intent = new Intent();
                intent.putExtra(RESULT, true);
                setResult(IDENTIFY_CODE, intent);
                getCustomer();
                finish();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(UserActivity.this, message);
            }
        });
    }

    //组装用户信息
    private String makeData() {
        String name = "{'name':'" + realNameEdt.getText().toString().trim() + "',";
        String id = "'uuid':'" + uuid + "',";
        String nickname = "'nickname':'" + nickNameEdt.getText().toString().trim() + "',";
        String sex = "'sex':'" + changeSexToNumber(sexTxt.getText().toString()).trim() + "',";
        String schoolName = "'schoolName':'" + schoolTxt.getText().toString().trim() + "',";
//        String schoolId = "'schoolId':'" + 8 + "',";
        String schoolId = "'schoolId':'" + schoolIdTxt.getText().toString().trim() + "',";
        String studentNum = "'studentNum':'" + numEdt.getText().toString().trim() + "',";
        String profession = "'profession':'" + specialtyEdt.getText().toString().trim() + "',";
        String headUrl = "'headUrl':'" + newHeadUrl + "',";
        String grade = "'grade':'" + dateTxt.getText().toString().trim() + "',";
        String address = "'address':'" + addressEdt.getText().toString().trim() + "'}";
        return name + id + nickname + sex + schoolName + grade + headUrl + schoolId + studentNum + profession + address;
    }

    private String changeSexToNumber(String sex) {
        if(sex.equals(getResources().getString(R.string.txt_male))){
            return "1";
        }
        return "2";
    }

    public static int getLength(String s) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        // 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
        for (int i = 0; i < s.length(); i++) {
            // 获取一个字符
            String temp = s.substring(i, i + 1);
            // 判断是否为中文字符
            if (temp.matches(chinese)) {
                // 中文字符长度为2
                valueLength += 2;
            } else {
                // 其他字符长度为1
                valueLength += 1;
            }
        }
        return valueLength;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_PICTURE:
                if (resultCode == this.RESULT_OK) {
                    Uri selectedImage = data.getData();

                    selectedImage = Uri.fromFile(new File(PicUtil.getPath(this, selectedImage)));

                    Intent selectIntent = new Intent();
                    selectIntent.setAction("com.android.camera.action.CROP");
                    selectIntent.setDataAndType(selectedImage, "image/*");// mUri是已经选择的图片Uri
                    selectIntent.putExtra("crop", "true");
                    selectIntent.putExtra("aspectX", 1);// 裁剪框比例
                    selectIntent.putExtra("aspectY", 1);
                    selectIntent.putExtra("outputX", 150);// 输出图片大小
                    selectIntent.putExtra("outputY", 150);
                    selectIntent.putExtra("return-data", true);
                    startActivityForResult(selectIntent, GET_CUT_PICTURE);
                }
                break;
            case TAKE_PHOTO:
                if (resultCode == this.RESULT_OK) {
                    Intent takeIntent = new Intent();
                    takeIntent.setAction("com.android.camera.action.CROP");
                    takeIntent.setDataAndType(takePhotoUri, "image/*");// mUri是已经选择的图片Uri
                    takeIntent.putExtra("crop", "true");
                    takeIntent.putExtra("aspectX", 1);// 裁剪框比例
                    takeIntent.putExtra("aspectY", 1);
                    takeIntent.putExtra("outputX", 150);// 输出图片大小
                    takeIntent.putExtra("outputY", 150);
                    takeIntent.putExtra("return-data", true);
                    startActivityForResult(takeIntent, GET_CUT_PICTURE);
                }
                break;
            case GET_CUT_PICTURE:
                if (resultCode == this.RESULT_OK) {
                    Bitmap bmap = data.getParcelableExtra("data");
                    upLoadPhoto(bmap);
                }
                break;
            case WheelViewActivity.CODE:
                if (data != null) {
                    Bundle b = data.getExtras();
                    schoolName = b.getString(WheelViewActivity.NAME);
                    schoolId = b.getInt(WheelViewActivity.ID);
                    schoolTxt.setText(schoolName);
                    schoolIdTxt.setText(String.valueOf(schoolId));
                }
                break;
            case WheelViewActivity.DATE:
                if (data != null) {
                    Bundle b = data.getExtras();
                    date = b.getString(WheelViewActivity.DATE_IDENT);
                    dateTxt.setText(date);
                }
                break;
        }
    }


    private void upLoadPhoto(Bitmap selectedImage) {
        final Bitmap bitmap = imageZoom(selectedImage);
        Log.e("++++压缩后bitmap大小", bitmap.getByteCount() / 1024 + "");
        final String bitmapString = Base64.encode(bitmap2Bytes(bitmap));
        Log.e("++++编码后的bitmapString大小", bitmapString.getBytes().length / 1024 + "");
        appAction.upload(getUploadString("png", bitmapString), "firstPicture", new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                Log.e("++++++头像上传成功,这是头像的地址 ", data);
                getHeadImg(data);
                newHeadUrl = data;
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e("++++成功了吗", "呵呵，不成功" + message);
                ToastUtil.showShort(UserActivity.this, "上传头像失败了亲, 再试一次好吗");
            }
        });
    }

    private void getHeadImg(String data) {
        XYApplication.getImageLoader().displayImage(PropertiesUtil.getImageServer() + data, headImg);
    }

    private Bitmap imageZoom(Bitmap bitMap) {
        Log.e("+++++bitmap size big", bitMap.getByteCount() / 1024 + "");
        //图片允许最大空间   单位：KB
        double maxSize = MAX_PIC_SIZE;
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        Log.e("+++++bitmap size", mid + "");
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
//            Log.e("+++++bitmap i", i+"");
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
                    bitMap.getHeight() / Math.sqrt(i));

        }
        Log.e("+++++bitmap size small", bitMap.getByteCount() / 1024 + "");
        return bitMap;
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    public byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private String getUploadString(String png, String bitmapString) {
        return png + "@" + bitmapString;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("编辑个人信息页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("编辑个人信息页");
        MobclickAgent.onPause(this);
    }

    private void NormalListDialogNoTitle() {
        final ArrayList<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        DialogAdapter dialogAdapter = new DialogAdapter(this, sexList);
        final NormalListDialog dialog = new NormalListDialog(this, dialogAdapter);
        dialog.title("请选择")//
                .isTitleShow(false)//
                .itemPressColor(Color.parseColor("#85D3EF"))//
                .itemTextColor(Color.parseColor("#303030"))//
                .layoutAnimation(null)
                .itemTextSize(15)//
                .cornerRadius(2)//
                .widthScale(0.75f)//
                .show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
//                T.showShort(MainActivity.this, sexList.get(position));
//                ToastUtil.showShort(UserActivity.this, position + "");
                displaySex(position);
                dialog.dismiss();
            }
        });
    }

    private void displaySex(int position) {
        if(position == 0){
            sexTxt.setText(getResources().getString(R.string.txt_male));
        }else {
            sexTxt.setText(getResources().getString(R.string.txt_female));
        }
    }

    @Override
    public void finish() {
        if(TextUtils.isEmpty(index)) {
            super.finish();
        } else {
            Intent intent = new Intent(this, MainTabActivity.class);
            intent.putExtra(MainTabActivity.INDEX, MainTabActivity.TAG_USER);
            startActivity(intent);
        }
    }
}
